﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Controlslib.Toolstrip
{
    public class HostableControlBase<T> : ToolStripDropDown, IHostableControl where T : Control, new()
    {
        public event EventHandler<HostableControlEvent> OnEventOccurred;

        private Action<Object, EventArgs> m_eventSink = null;
        private T m_control = default(T);

        public HostableControlBase()
        {
            m_control = new T();

            ((IHostableControl)m_control).OnEventOccurred += new EventHandler<HostableControlEvent>(HostableControlBase_OnEventOccurred);

            Items.Add(new ToolStripControlHost(m_control));
        }

        public HostableControlBase(Action<Object, EventArgs> eventSink)
        {
            m_control = new T();

            m_eventSink = eventSink;

            ((IHostableControl)m_control).OnEventOccurred += new EventHandler<HostableControlEvent>(HostableControlBase_OnEventOccurred);

            Items.Add(new ToolStripControlHost(m_control));
        }

        void HostableControlBase_OnEventOccurred(object sender, HostableControlEvent e)
        {
            if (m_eventSink != null)
            {
                m_eventSink.Invoke(sender, e);
            }
            else
            {
                if (OnEventOccurred != null)
                {
                    OnEventOccurred(sender, new HostableControlEvent(e));
                }
            }
        }

        public T Control
        {
            get { return this.m_control; }
        }

        protected override void OnOpening(System.ComponentModel.CancelEventArgs e)
        {
            base.OnOpening(e);
        }

        protected override void OnOpened(EventArgs e)
        {
            base.OnOpened(e);
        }
    }
}
